<template>
  <div class="write-article">
    <div class="container">
      <h1 class="page-title">写博客</h1>
      <form @submit.prevent="handleSubmit" class="article-form">
        <div class="form-group">
          <label for="title">文章标题</label>
          <input
            type="text"
            id="title"
            v-model="article.title"
            class="form-control"
            required
          >
        </div>

        <div class="form-group">
          <label for="content">文章内容</label>
          <textarea
            id="content"
            v-model="article.content"
            class="form-control"
            rows="10"
            required
          ></textarea>
        </div>

        <div class="form-group">
          <label for="tags">文章标签</label>
          <input
            type="text"
            id="tags"
            v-model="tagsInput"
            class="form-control"
            placeholder="输入标签，用逗号分隔"
          >
        </div>

        <div class="form-group">
          <label class="checkbox-label">
            <input
              type="checkbox"
              v-model="article.is_published"
            >
            立即发布
          </label>
        </div>

        <div class="form-actions">
          <button type="submit" class="btn btn-primary">保存文章</button>
          <button type="button" class="btn btn-secondary" @click="handlePreview">预览</button>
        </div>
      </form>

      <!-- 预览模态框 -->
      <div v-if="showPreview" class="preview-modal">
        <div class="preview-content">
          <h2>{{ article.title }}</h2>
          <div class="preview-meta">
            <span>作者: {{ currentUser }}</span>
            <span>发布状态: {{ article.is_published ? '已发布' : '草稿' }}</span>
          </div>
          <div class="preview-body">
            {{ article.content }}
          </div>
          <div class="preview-tags">
            <span v-for="tag in article.tags" :key="tag" class="tag">{{ tag }}</span>
          </div>
          <button class="btn btn-secondary" @click="showPreview = false">关闭预览</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed,onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { articleApi } from '@/api/api'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const router = useRouter()
// const currentUser = ref('当前用户') // 这里应该从用户状态获取
// 如果需要在组件挂载时动态检查用户状态
onMounted(() => {
  console.log('isLoggedIn:', userStore.isLoggedIn)
  console.log('userId:', userStore.userId)
  if (!userStore.isLoggedIn) {
    router.push('/login')
  } else {
    article.value.author_id = userStore.userId || null
  }
})

const article = ref({
  author_id: userStore.userId || null,  // 初始化时取 userId，若为空则为 null
  title: '',
  content: '',
  tags: [],
  is_published: false
})

const tagsInput = ref('')
const showPreview = ref(false)

// 处理标签输入
const handleTagsInput = () => {
  article.value.tags = tagsInput.value.split(',').map(tag => tag.trim()).filter(tag => tag)
}

// 预览文章
const handlePreview = () => {
  handleTagsInput()
  showPreview.value = true
}
// 提交文章
const handleSubmit = async () => {
  if (!userStore.isLoggedIn || !userStore.userId) {
    alert('请先登录！')
    router.push('/login')
    return
  }
  article.value.author_id = userStore.userId  // 提交前强制更新
  handleTagsInput()
  console.log('提交的数据:', article.value)
  try {
    const response = await articleApi.createArticle(article.value)
    console.log('后端响应:', response)
    router.push('/blog')
  } catch (error) {
    console.error('保存文章失败：', error)
    alert('保存文章失败，请稍后重试')
  }
}
</script>

<style scoped>
.write-article {
  padding: 2rem 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 1rem;
}

.page-title {
  margin-bottom: 2rem;
  text-align: center;
}

.article-form {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.form-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.form-control {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

textarea.form-control {
  resize: vertical;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.form-actions {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
}

.btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.preview-content {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  max-width: 800px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.preview-meta {
  margin: 1rem 0;
  color: #666;
  display: flex;
  gap: 1rem;
}

.preview-body {
  margin: 2rem 0;
  white-space: pre-wrap;
}

.preview-tags {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  margin-bottom: 1rem;
}

.tag {
  background: #e9ecef;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.875rem;
}
</style>